<template>
  <div class="w-[290px] h-full flex flex-col justify-between bg-[#FFFFFF] border-right">
    <div class="tabs" v-if="premsStore.isEditChatSetting">
      <div
        class="tab-item relative"
        @click="handleClick(index)"
        :class="{
          active: mainState.tabActive == 0 && index == mainState.tabActive,
          active1: mainState.tabActive == 1 && index == mainState.tabActive
        }"
        v-for="(name, index) in tabs"
      >
        {{ name }}
        <i
          v-if="status && index == 1"
          class="absolute top-[2px] right-[10px] w-[8px] h-[8px] bg-red-500 rounded-[5px]"
        ></i>
      </div>
    </div>
    <div class="grow-[1] h-0 overflow-hidden border-top" v-if="mainState.tabActive == 0">
      <el-scrollbar always class="w-full h-full overflow-hidden" v-loading="mainState.loading">
        <div class="h-[10px]"></div>
        <template v-for="(item, index) in gameTotal">
          <article
            class="game-item"
            :class="{
              'bg-[#DFEFFF]': index == mainState.gameActive
            }"
            @click="handleGame(index)"
          >
            <div class="w-[48px] h-[48px] rounded-[48px]">
              <img
                class="block overflow-hidden w-[48px] h-[48px] rounded-[48px]"
                :src="lotteryLogo(item.LotteryId)"
              />
            </div>
            <div class="flex-1 w-0 ml-[6px]">
              <div class="flex justify-between items-center">
                <span class="text-[15px] text-[#111111]">{{ item.Name }}</span>
                <el-switch
                  @click.stop=""
                  size="large"
                  v-model="item.Status"
                  :active-value="1"
                  class="!h-[30px]"
                  :inactive-value="0"
                  :before-change="() => changeLotteryStatus(item)"
                />
              </div>
              <div class="flex justify-between">
                <span class="text-gray-400 text-[12px]">{{ item.Issue }}期</span>
              </div>
            </div>
          </article>
        </template>
        <div class="h-[10px]"></div>
      </el-scrollbar>
    </div>
    <div
      class="grow-[1] h-0 overflow-hidden flex flex-col justify-between"
      v-if="mainState.tabActive == 1"
    >
      <div class="flex items-center px-[10px] pb-[10px]">
        <el-input
          class="!mr-[5px] flex-1"
          v-model="serviceState.Name"
          placeholder="备注/昵称"
        ></el-input>
        <el-select class="!w-[100px]" v-model="serviceState.SortField" placeholder="请选择排序">
          <el-option label="在线排序" value="online" />
          <el-option label="最后聊天" value="time" />
          <el-option label="积分排序" value="coin" />
        </el-select>
        <el-button class="!w-[60px] ml-[5px]" type="primary" @click="handleSearchKefu">
          搜索
        </el-button>
      </div>
      <el-scrollbar
        always
        class="grow-[1] h-0 overflow-hidden"
        v-loading="loading"
        ref="kefuScrollRef"
      >
        <div
          class="w-full h-full flex justify-center items-center"
          v-if="!loading && serviceList.length == 0"
        >
          <ui-empty />
        </div>
        <article
          :id="`user-item-${item.UserId}`"
          class="user-item relative"
          :class="{
            'bg-[#DFEFFF]': index == mainState.serviceActive
          }"
          @click="handleService(index)"
          v-for="(item, index) in serviceList"
        >
          <!-- 未读消息数 -->
          <span v-if="item.Count > 0" class="tip-num">
            {{ item.Count! > 99 ? 99 : item.Count }}
          </span>
          <div class="flex-1 w-0">
            <div class="flex items-center">
              <div class="flex items-center mr-[5px]">
                <div
                  class="w-[10px] h-[10px] rounded-[10px]"
                  :class="{
                    'bg-gray-300': item.Online === 0,
                    'bg-[#67C23A]': item.Online === 1
                  }"
                ></div>
              </div>
              <div class="w-[36px] h-[36px] rounded-[36px]">
                <avatar :size="36" :round="36" :src="item.Avatar" />
              </div>
              <div class="flex-1 w-0 ml-[6px] h-[36px] flex items-center">
                <span class="!text-[14px] text-[#333]">
                  {{ item.Note || item.NickName || item.Name }}
                </span>
              </div>
            </div>
            <div class="text-gray-400 text-[12px] mt-[4px]">
              最近上线时间:{{ userTimeAgo(new Date(formatDate(item.LastMsgTime))) }}
            </div>
          </div>
          <el-popover popper-class="service-popover" placement="right" :width="200" trigger="click">
            <ul class="!text-[15px]">
              <li
                class="py-[10px] cursor-pointer text-center border-bottom"
                @click="handleEditNote(item)"
              >
                修改会员备注
              </li>
              <el-dropdown
                class="dropdown-popover"
                placement="bottom"
                @command="(e: number) => handleChangeStatus(item, e)"
              >
                <li
                  class="h-full w-full flex items-center !text-[15px] cursor-pointer justify-center border-bottom"
                >
                  修改会员状态
                </li>
                <template #dropdown>
                  <el-dropdown-item :disabled="item.Status == 1" :command="1">
                    <div class="w-full text-center">正常</div>
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="item.Status == 0" :command="0">
                    <div class="w-full text-center">停用</div>
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="item.Status == 2" :command="2">
                    <div class="w-full text-center">禁言</div>
                  </el-dropdown-item>
                  <el-dropdown-item :disabled="item.Status == 3" :command="3">
                    <div class="w-full text-center">禁止加入房间</div>
                  </el-dropdown-item>
                </template>
              </el-dropdown>
              <li class="py-[10px] cursor-pointer text-center" @click="handleDel(item)">
                删除会员聊天
              </li>
            </ul>
            <template #reference>
              <div @click.stop="">
                <div class="flex items-center justify-end">
                  <el-icon class="!text-[16px] mr-[15px]" color="#666"><MoreFilled /></el-icon>
                </div>
                <el-button :type="statusMap[item.Status].type" size="small">
                  {{ statusMap[item.Status].text }}
                </el-button>
              </div>
            </template>
          </el-popover>
        </article>
        <div class="h-[10px]"></div>
      </el-scrollbar>
    </div>
    <div class="p-[20px] py-[15px] border-top">
      <section class="text-[16px] font-bold">
        <span>在线人数</span>
        <span>{{ onlineData.count }}</span>
      </section>
      <section class="text-[11px] mt-[10px]">
        上次登录时间: {{ formatDate(onlineData.lastDate) }}
      </section>
    </div>
    <template v-if="serviceList.length">
      <edit-note-dialog
        ref="editNoteDialogRef"
        :data="serviceList[mainState.serviceActive]"
        @update="getServiceList"
      />
    </template>
  </div>
</template>
<script setup lang="ts">
import editNoteDialog from "./edit-note-dialog.vue";

import $bus from "@/utils/bus";
import { storeToRefs } from "pinia";
import { lotteryLogo } from "@/utils/game";
import { useUserStore } from "@/store/modules/user";
import { useGameStore } from "@/store/modules/game";
import { useSocketStore } from "@/store/modules/socket";
import { useServiceStore } from "@/store/modules/service";
import { formatDate, userTimeAgo } from "@/utils/common";
import { SocketStatus } from "@/enums";
import { reqChatContentDel, reqOnlineCount, reqSwitchStatus } from "@/api/main";
import { message } from "@/utils/message";
import { reqUserBan } from "@/api/user";
import { ElMessageBox } from "element-plus";
import { usePremsStore } from "@/store/modules/prems";

const route = useRoute();
const router = useRouter();
const gameStore = useGameStore();
const premsStore = usePremsStore();
const userStore = useUserStore();
const serviceStore = useServiceStore();
const socket = useSocketStore();
const { gameTotal } = storeToRefs(gameStore);
const { userInfo } = storeToRefs(userStore);
const { status, serviceList, serviceState } = storeToRefs(serviceStore);
const loading = ref(false);
const mainState = inject("mainState")! as MainState;
const editNoteDialogRef = ref();
const kefuScrollRef = ref();
const onlineData = reactive({
  count: 0,
  lastDate: ""
});

const tabs = ref(["游戏", "客服"]);
let flag = false;

const statusMap = reactive<Record<string, TextType>>({
  0: { text: "停用", type: "danger" },
  1: { text: "正常", type: "success" },
  2: { text: "禁言", type: "danger" },
  3: { text: "禁止加入房间", type: "danger" }
});

const getGameTotal = async () => {
  if (gameTotal.value.length == 0) {
    mainState.loading = true;
  }
  if (!flag) {
    await gameStore.actionGameTotal();
    mainState.loading = false;
    flag = true;
  }
  nextTick(() => {
    $bus.emit("game-switch");
  });
};

const getServiceList = async () => {
  if (serviceList.value.length == 0) {
    loading.value = true;
  }
  console.log(mainState.serviceActive);
  serviceState.value.Page = 1;
  serviceState.value.TotalPage = 99999;
  await serviceStore.actionServiceList().then(() => {
    nextTick(() => {
      scrollToUserItem(serviceList.value[mainState.serviceActive]);
    });
  });
  loading.value = false;
  nextTick(() => {
    $bus.emit("service-switch");
  });
};

// 切换tab
const handleClick = async (index: number) => {
  mainState.tabActive = index;
  mainState.unreadMessage = 0;
  mainState.autoScrollToBottom = true;
  nextTick(() => {
    if (index == 0) {
      joinRoom(mainState.gameActive);
      getGameTotal();
      router.replace({ path: "/admin/main" });
    }
    if (index == 1) {
      outRoom(mainState.gameActive);
      getServiceList();
    }
  });
};

// 切换游戏
const handleGame = async (index: number) => {
  mainState.gameActive = index;
  nextTick(() => {
    $bus.emit("game-switch");
  });
};

// 切换客服
const handleService = (index: number) => {
  mainState.serviceActive = index;
  serviceList.value[index].Count = 0;
  nextTick(() => {
    $bus.emit("service-switch");
  });
};

// 修改游戏开关
const changeLotteryStatus = async (item: GameTotalMo) => {
  return new Promise(async (resolve, reject) => {
    try {
      await reqSwitchStatus({
        LotteryId: item.LotteryId,
        Status: item.Status == 1 ? 0 : 1
      });
      item.Status = item.Status == 1 ? 0 : 1;
      gameStore.actionGameTotal();
      message.success("修改游戏状态成功");
      return resolve(true);
    } catch (error) {
      return reject(error);
    }
  });
};

// 搜索客服列表
const handleSearchKefu = async () => {
  serviceState.value.Page = 1;
  await serviceStore.actionServiceList();
};

const getOnlineCount = async () => {
  try {
    const res = await reqOnlineCount();
    console.log(res);
    onlineData.count = res.data.count;
    onlineData.lastDate = formatDate(res.data.lastDate);
  } catch (error) {
    console.log(error);
  }
};

// 加入房间
const joinRoom = (index: number) => {
  const lotteryId = gameTotal.value[index].LotteryId;
  const roomName = `${userInfo.value?.RoomId}_${lotteryId}`;
  socket.client?.emit("joinroom", {
    roomName,
    userId: userInfo.value?.Id,
    nickName: userInfo.value?.Name,
    sendType: "PUBLIC"
  });
};

// 退出房间
const outRoom = (index: number) => {
  const lotteryId = gameTotal.value[index].LotteryId;
  const roomName = `${userInfo.value?.RoomId}_${lotteryId}`;
  socket.client?.emit("leaveroom", { roomName });
};

// 修改状态
const handleChangeStatus = async (row: ChatContentMo, key: number) => {
  try {
    loading.value = true;
    await reqUserBan({
      UserId: Number(row.UserId),
      Status: key
    });
    message.success("修改状态成功");
    loading.value = false;
    row.Status = key;
  } catch (error) {
    loading.value = false;
    console.log(error);
  }
};

// 删除
const handleDel = (row: ChatContentMo) => {
  ElMessageBox.confirm(`是否进行【删除】操作`, "", {
    confirmButtonText: "确认",
    cancelButtonText: "取消",
    type: "warning",
    distinguishCancelAndClose: true,
    beforeClose: async (action, instance, done) => {
      if (action === "confirm") {
        try {
          instance.confirmButtonLoading = true; // 设置 "确定" 按钮加载中
          await reqChatContentDel({
            Id: row.Id
          });
          message.success("删除成功");
          handleSearchKefu();
          serviceStore.removeService(row);
          mainState.serviceActive = 0;
          setTimeout(() => {
            kefuScrollRef.value?.setScrollTop(0);
          });
          nextTick(() => {
            $bus.emit("service-switch");
          });
          done(); // 操作成功后关闭对话框
          instance.confirmButtonLoading = false;
        } catch (error) {
          done();
          console.error("操作失败", error);
          instance.confirmButtonLoading = false; // 如果失败，取消加载状态
        }
      } else {
        done(); // 取消时直接关闭
      }
    }
  });
};

const handleEditNote = (item: ChatContentMo) => {
  editNoteDialogRef.value?.open(item);
};

const scrollToUserItem = (item: ChatContentMo) => {
  const dom = document.getElementById(`user-item-${item.UserId}`) as HTMLDivElement;
  if (dom) {
    setTimeout(() => {
      kefuScrollRef.value?.setScrollTop(dom.offsetTop);
    });
  }
};

const watchSocket = () => {
  $bus.on("open-result", async () => {
    // await gameStore.actionGameTotal();
  });
  $bus.on("game-bet", async () => {
    // await gameStore.actionGameTotal();
  });
  // 监听切换客服
  $bus.on("switch-kefu-item", async (uid: string) => {
    const index = serviceList.value.findIndex(item => String(item.UserId) === String(uid));
    handleService(index);
    scrollToUserItem(serviceList.value[index]);
  });
  // 监听游戏tan切换到客服
  $bus.on("switch-kefu-tab", async (uid: string) => {
    outRoom(mainState.gameActive);
    mainState.serviceActive = serviceList.value.findIndex(
      item => String(item.UserId) === String(uid)
    );
    mainState.tabActive = 1;
    await getServiceList();
  });

  if (mainState.tabActive == 0) {
    if (socket.status == SocketStatus.CONNECTED) {
      joinRoom(mainState.gameActive);
    } else {
      $bus.on("init-socket", async () => {
        joinRoom(mainState.gameActive);
      });
    }
  }
};

watch(
  () => mainState.gameActive,
  async (val, old) => {
    mainState.loading = true;
    await outRoom(old);
    setTimeout(() => {
      joinRoom(val);
    }, 200);
  }
);
let timer: any;
onBeforeMount(async () => {
  await getGameTotal();
  watchSocket();
  if (route.query.kefu) {
    outRoom(mainState.gameActive);
    mainState.tabActive = 1;
    mainState.serviceActive = serviceList.value.findIndex(
      item => item.UserId == (route.query.kefu as string)
    );
    await getServiceList();
  }
  getOnlineCount();
  timer = setInterval(() => {
    getOnlineCount();
    gameStore.actionGameTotal();
  }, 10000);
});

onBeforeUnmount(async () => {
  if (mainState.tabActive == 0) {
    await outRoom(mainState.gameActive);
  }
  clearInterval(timer);
  timer = null;
});
</script>
<style>
.service-popover {
  padding: 0 !important;
}
.dropdown-popover {
  height: 40px;
  line-height: 40px;
  display: flex;
  justify-content: center;
  align-items: center;
}
</style>
<style scoped>
.tabs {
  @apply w-[180px] h-[36px] rounded-[36px] bg-[#ECF4FF] mx-auto my-[12px];
  @apply flex justify-between items-center;
}
.tab-item {
  @apply flex-1 flex justify-center items-center text-gray-600;
  @apply h-[36px] cursor-pointer;
  @apply text-[14px];
}
.tab-item.active {
  border-radius: 30px 0 0 30px;
  color: #fff;
  background: #0087b4;
}
.tab-item.active1 {
  border-radius: 0 30px 30px 0;
  color: #fff;
  background: #0087b4;
}
.game-item {
  margin-bottom: 5px;
}
.game-item,
.user-item {
  @apply px-[7px] py-[10px] mx-[10px] flex justify-between items-center;
  @apply rounded-[4px] cursor-pointer;
}
.tip-num {
  @apply rounded-[10px] flex justify-center items-center text-white absolute top-[2px] right-[5px] w-[18px] h-[18px] bg-red-500;
}
</style>
